//
//  SetupController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/6/21.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "SetupController.h"
#import "DefaultButton.h"
#import "regardingController.h"
#import "SuggestionsController.h"



@interface SetupController ()
{
    MBProgressHUD *progressHUD;
}

@property(nonatomic,strong)NSString *cachePath;

@end

@implementation SetupController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.title = @"设置";
    self.tableView.backgroundColor = BACKGROUND_COLOR;
    
    //cache路径
    self.cachePath = [ NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else{
        return 3;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"SetupControllerCell";
    
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell==nil) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.font = FONT(15);
    }
    
    NSArray *setArr = @[@"关于亿乐Go",@"清除缓存",@"意见反馈",@"评价我们"];
    
    if (indexPath.section == 0) {
        cell.textLabel.text = [NSString stringWithFormat:@"%@",setArr[indexPath.row]];
    }else{
        cell.textLabel.text = [NSString stringWithFormat:@"%@",setArr[indexPath.row+1]];
    }
    
    //计算cache多少M
    float fileSize = [self folderSizeAtPath:_cachePath];
    if (indexPath.section == 1&& indexPath.row == 0) {
        cell.detailTextLabel.font = FONT(14);
        cell.detailTextLabel.text = fileSize >= 1 ? [NSString stringWithFormat:@"已使用%.2fM",fileSize] : [NSString stringWithFormat:@"已使用%.2fK",fileSize * 1024];
    }
    
    return cell;
}


#pragma mark >>>>>>>>>>>代理

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        //关于亿乐
        regardingController *regardingVC = [[regardingController alloc] init];
        [self.navigationController pushForm:self.navigationController pushToAndHidden:regardingVC];
    }else if (indexPath.row == 2 && indexPath.section == 1){
        
        //跳转评论
        NSURL * url = [NSURL URLWithString:@"itms-apps://itunes.apple.com/cn/app/yi-le-gou-wu-ba/id1107627163?mt=8"];
        if ([[UIApplication sharedApplication] canOpenURL:url])
        {
            [[UIApplication sharedApplication] openURL:url];
        }
        else
        {
            NSLog(@"can not open");
        }
        
    }else if (indexPath.row == 1 && indexPath.section == 1 ){
        
        SuggestionsController *sugg = [[SuggestionsController alloc] init];
        [self.navigationController pushForm:self.navigationController pushToAndHidden:sugg];
        
    } else {
        
        //清除缓存
        [self clearUserCacheData];
        
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    if (section == 0) {
        return 0.01;
    }else{
        return HEIGHT/6;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }else{
        return [self leaveView];
    }
}

#pragma mark 清除缓存
- ( void )clearUserCacheData
{
    
    NSArray * files = [[ NSFileManager defaultManager ] subpathsAtPath :self.cachePath];
    for ( NSString * fileName in files) {
        NSError * error = nil ;
        NSString * path = [_cachePath stringByAppendingPathComponent :fileName];
        if ([[ NSFileManager defaultManager ] fileExistsAtPath :path]) {
            [[ NSFileManager defaultManager ] removeItemAtPath :path error :&error];
            
        }
        
    }
    
    [ self performSelectorOnMainThread : @selector (clearCachSuccess) withObject :nil waitUntilDone : YES ];
    
}

- (void)clearCachSuccess
{
    MBProgressHUD *hud = [MBProgressHUD showMessage:@"缓存清除" toView:self.view dimBackground:NO AndCompleteBlock:nil];
    [self.view addSubview:hud];
    hud.removeFromSuperViewOnHide = YES;
    [progressHUD removeFromSuperview];
    [self.tableView reloadData];
}

//遍历文件夹获得文件夹大小
- (float ) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}

- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

- (UIView *)leaveView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,WIDTH, HEIGHT/6)];
    DefaultButton *button = [[DefaultButton alloc] init];
    [button setTitle:@"退出当前账户" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(exitUserAccount) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(view.mas_centerX);
        make.centerY.equalTo(view.mas_centerY);
        make.height.mas_equalTo(view.Height/3);
        make.width.mas_equalTo(WIDTH-30);
    }];
    return view;
}

- (void)exitUserAccount
{
    [ReadLoginData cleanloginData];
    [self.navigationController popViewControllerAnimated:YES];
    
}

@end
